#include "common.hpp"

int main()
{
    //1、获取共享内存的关键码
    int key=getkey();
    cout<<"getkey success  key："<<key<<endl;

    //2、创建共享内存
    int shmid=createShm(key);
    cout<<"createShm success  shmid:"<<shmid<<endl;

    //3、挂接共享内存
    char* start=(char*)attachShm(shmid);
    printf("attachShm success  共享内存起始地址：%p\n",start);

    //4、通信(从共享内存读取数据)
    int cnt=1;
    while(true)
    {
        //直接读取共享内存的数据
        printf("client say:%s | server_pid:%d\n",start,getpid());
        sleep(2);//每隔两秒读一次
    }


    //5、取消挂接
    int res=shmdt(start);
    if(res==-1)//操作失败
    {
        cout<<"delete attachshm failed"<<endl;
        deleteShm(shmid);//删除共享内存
        cout<<"deleteShm success"<<endl;
        exit(-1);//结束进程
    }
    else//取消挂接成功
    {
        cout<<"delete attachshm success"<<endl;
    }

    //6、删除共享内存
    deleteShm(shmid);//删除共享内存
    cout<<"deleteShm success"<<endl;

    return 0;
}